import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
import router from '@/router'
const request = axios.create({
  baseURL: 'http://geek.itheima.net'
  // baseURL: 'http://toutiao.itheima.net'
})

// 添加请求拦截器
request.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const token = store.state.user.tokenObj.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
request.interceptors.response.use(function (response) {
  // 做数据剥离
  return response.data
},

async function (error) {
  if (error.response.status === 401) {
    try {
      const res = await axios({
        url: 'http://geek.itheima.net/v1_0/authorizations',
        method: 'put',
        headers: {
          Authorization: `Bearer ${store.state.user.tokenObj.refresh_token}`
        }
      })
      store.commit('user/setToken', {
        token: res.data.data.token,
        refresh_token: store.state.user.tokenObj.refresh_token
      })
      return request(error.config)
    } catch {
      Toast.fail('登录已失效，请重新登录')
      router.push('/login')
    }
  } else {
    return Promise.reject(error)
  }
})
export default request
